﻿function InitDatatable() {
    if ($('.krmtable').length > 0) {
        $('.krmtable').each(function () {
          LoadDataTable($(this));
        });
    }
}

function InitAjaxTable(table) {
    LoadDataTable(table);
}
function InitTableSelected() {
    $(".tbl-selected tbody tr").click(function () {
        $(this).addClass("row-selected");
        $(this).parent().find("tr").not(this).removeClass('row-selected');
    });
}

function InitDatetimePicker() {
    $('.datetimepicker').datetimepicker({
        language: 'en',
        pick12HourFormat: true
    });
}
function InitTabs() {
    $('.tabs a').click(function (e) {
        e.preventDefault();
        $(this).tab('show');
    });
};
$(document).ready(function () {
    gadientlogo($(".navbar-brand img"));
    //releasekrm();
    createtrigger();
    //$(".validaterdm").validate();
    getSelectValMultiple();
    InitDatatable();
    $('.p-advance').click(function () {
        $('.panel-advance').slideToggle("fast");
    });

    onTaskSort();

    $('#frCreateTrigger').submit(function () {
        var serializedForm = $(this).serialize();
        $(".bodyhf-createtrigger").hide();
        $(".body-createtrigger").append("<div class='ajax-loadForm'></div>");
        $.ajax({
            type: 'POST',
            url: '/scenario/createtrigger',
            data: serializedForm,
            success: function (data) {
                $(".ajax-loadForm").hide();
                $(".bodyhf-createtrigger").show();
                $(".msg-trigger").html(data);
            }
        });
        return false;
    });

    $("#ReasonID").change(function () {
        var selectedItem = $(this).val();
        var ddlDetail = $("#ReasonDetailID");
        var ddlLiability = $("#LiabilityID");
        var orderid = $("#OrderItemID").val();
        $.ajax({
            cache: false,
            url: "/rdm/getreasondetailbyreason",
            data: { "reasonid": selectedItem, "orderitemid": orderid },
            success: function (data) {
                ddlDetail.html('');
                ddlDetail.append($('<option></option>').html("Please select a Reason Detail"));
                $.each(data, function (id, option) {
                    ddlDetail.append($('<option></option>').val(option.id).html(option.name));
                });
                $.ajax({
                    cache: false,
                    url: "/rdm/getliabilitybyreason",
                    data: { "reasonid": selectedItem },
                    success: function (data) {
                        ddlLiability.html('');
                        $.each(data, function (id, option) {
                            ddlLiability.append($('<option></option>').val(option.id).html(option.name));
                        });
                    }
                });
            },
            error: function (xhr, ajaxOptions, thrownError) {
                $.ajax({
                    cache: false,
                    url: "/rdm/getliabilitybyreason",
                    data: { "reasonid": selectedItem },
                    success: function (data) {
                        ddlLiability.html('');
                        $.each(data, function (id, option) {
                            ddlLiability.append($('<option></option>').val(option.id).html(option.name));
                        });
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert('Failed to retrieve liability.');
                    }
                });
            }
        });
    });

    $(".issueresolve").click(function () {
        $(".questionaireform").attr("action", "/rdm/issueresolvel");
        $(this).attr('type', 'submit');
        $(this).trigger('click');
    });
    $(".savequestionnaire").click(function () {
        $(".questionaireform").attr("action", "/rdm/QuestionnaireForm");
        $(this).attr('type', 'submit');
        $(this).trigger('click');
    });

    $(".btn-issueresolve").click(function () {
        $(".addquestionaireform").attr("action", "/rdm/issueresolvel");
        $(".addquestionaireform").attr("action", "/rdm/GenerateRdm");
        if ($('#ReasonDetailID').val() == "Please select a Reason Detail") {
            alert("Please select a Reason Detail"); return;
        }
        $(this).attr('type', 'submit');
        $(this).trigger('click');
    });
    $(".btn-addquestionnaire").click(function () {
        $(".addquestionaireform").attr("action", "/rdm/AddQuestionnaireForm");
        $(".addquestionaireform").attr("action", "/rdm/GenerateRdm");
        if ($('#ReasonDetailID').val() == "Please select a Reason Detail") {
            alert("Please select a Reason Detail"); return;
        }
        $(this).attr('type', 'submit');
        $(this).trigger('click');
    });

    $(".btn-generaterdm").click(function () {
        $(".addquestionaireform").attr("action", "/rdm/GenerateRdm");
        if ($('#ReasonDetailID').val() == "Please select a Reason Detail") {
            alert("Please select a Reason Detail"); return;
        }
        $(this).attr('type', 'submit');
        $(this).trigger('click');
    });

    $(".btn-savequestionnairenon").click(function () {
        $(".addquestionnairenonfac").attr("action", "/rdm/AddQuestionnaireNonFac");
        if ($('#ReasonDetailID').val() == "Please select a Reason Detail") {
            alert("Please select a Reason Detail"); return;
        }
        $(this).attr('type', 'submit');
        $(this).trigger('click');
    });

    $(".btn-generaterdmnon").click(function () {
        $(".addquestionnairenonfac").attr("action", "/rdm/GenerateRdmNonFac");
        if ($('#ReasonDetailID').val() == "Please select a Reason Detail") {
            alert("Please select a Reason Detail"); return;
        }
        $(this).attr('type', 'submit');
        $(this).trigger('click');
    });

    $(".generaterdmnonfac").click(function () {
        $(".questionairenonfac").attr("action", "/rdm/GenerateRdmNonFac");
        $(this).attr('type', 'submit');
        $(this).trigger('click');
    });

    $(".issueresolvenonfac").click(function () {
        $(".questionairenonfac").attr("action", "/rdm/issueresolvelnonfac");
        $(this).attr('type', 'submit');
        $(this).trigger('click');
    });
    $(".savequestionnairenonfac").click(function () {
        $(".questionairenonfac").attr("action", "/rdm/QuestionnaireNonFac");
        $(this).attr('type', 'submit');
        $(this).trigger('click');
    });

    $(".btn-issueresolvenonfac").click(function () {
        $(".addquestionnairenonfac").attr("action", "/rdm/issueresolvelnonfac");
        if ($('#ReasonDetailID').val() == "Please select a Reason Detail") {
            alert("Please select a Reason Detail"); return;
        }
        $(this).attr('type', 'submit');
        $(this).trigger('click');
    });

    $("#sendapproval").click(function () {
        $("#hfDisputeStatusID").val('1');
        //$(this).attr('type', 'submit');
        //$(this).trigger('click');
        //if ($("#ResolutionID").val() == 3 || $("#ResolutionID").val() == 2 || $("#ResolutionID").val() == 1) {
        //    if (new Date($("#PreferredCollectionDate").val()) <= new Date()) {
        //        alert("You must enter a Preferred Collection Date. You entered a date in the past.");
        //        return;
        //    }
        //}
        if ($("#frsavedispute").valid()) {
            var dispute = $("#hfDisputeid").val() != undefined ? $("#hfDisputeid").val() : 0;
            $.ajax({
                url: "/rdm/countphoto",
                data: { id: dispute },
                success: function (data) {
                    if (data == 0) {
                        if (confirm("You haven't entered any photos for evidence, is this right?")) {
                            //$("#sendapproval").attr('type', 'submit');
                            $("#frsavedispute").submit();
                        }
                    } else {
                        $("#frsavedispute").submit();
                    }
                }
            });
        }

    });
    $("#saverdm").click(function () {
        $("#hfDisputeStatusID").val('4');
        $(this).attr('type', 'submit');
        $(this).trigger('click');
    });

    $("#cbnewcard").change(function () {
        if ($("#cbnewcard").is(':checked')) {
            $('.cardnumber, .expiry, .issuedate, .issue, .cv2').removeAttr('disabled');
            $("#cbTransactionId").attr('disabled', 'disabled');
        } else {
            $('.cardnumber, .expiry, .issuedate, .issue, .cv2').attr('disabled', 'disabled');
            $("#cbTransactionId").removeAttr('disabled');
        }
    });

    $(".tbl-orderitemdetail tbody tr").click(function () {
        $(this).addClass("row-selected");
        $(".tbl-orderitemdetail tbody tr").not(this).removeClass('row-selected');
    });

    $("#ResolutionID").change(function () {
        if ($(this).val() == 6) {
            $("#IsFullDisputeItems").attr('checked', 'checked');
            $("#IsFulDisputeReplacementItems").attr('checked', 'checked');
        }
    });

    $("#cbDespatchDate").change(function () {
        if ($("#cbDespatchDate").is(':checked')) {
            $('#despatchdate').removeAttr('disabled');
        } else {
            $("#despatchdate").attr('disabled', 'disabled');
        }
    });

    $("#cbDeliveryDate").change(function () {
        if ($("#cbDeliveryDate").is(':checked')) {
            $('#deliverydate').removeAttr('disabled');
        } else {
            $("#deliverydate").attr('disabled', 'disabled');
        }
    });

    $(".cbattachguideline").change(function () {
        if ($(this).is(':checked')) {
            $('.guidelineattach').show();
        } else {
            $('.guidelineattach').hide();
        }
    });

    var $table = $('.fixhead .table-fix');
    $table.floatThead({
        scrollContainer: function ($table) {
            return $table.closest('.fixhead');
        }
    });

    $("#frProductSearch").submit(function () {
        App.blockUI($('body'), false);
        var lstproducts = $("#lstProductSearch");
        var serializedForm = $(this).serialize();
        $.ajax({
            url: "/products/SearchProduct",
            data: serializedForm,
            cache: false,
            success: function (data) {
                lstproducts.html('');
                App.unblockUI($('body'));
                $.each(data, function (id, option) {
                    lstproducts.append($('<option></option>').val(option.id).html(option.name));
                });
            }
        });
        return false;
    });

    $("#fr-addvideo").submit(function () {
        if ($("#lstProductSearch").val() == null) {
            alert("Please select a product");
            return false;
        } else {
            App.blockUI($('body'), false);
            var serializedForm = $(this).serialize();
            $.ajax({
                url: "/products/productvideo",
                data: serializedForm,
                method: "POST",
                cache: false,
                success: function (data) {
                    App.unblockUI($('body'));
                    alert(data);
                }, error: function () {
                    App.unblockUI($('body'));
                    alert("Error!");
                }
            });
            return false;
        }
    });

    $("#btnallproductwvideo").click(function () {
        App.blockUI($('body'), false);
        var lstproducts = $("#lstProductSearch");
        $.ajax({
            url: "/products/allproductwithvideo?storeid=" + $("#StoreID").val(),
            cache: false,
            success: function (data) {
                lstproducts.html('');
                $.each(data, function (id, option) {
                    lstproducts.append($('<option></option>').val(option.id).html(option.name));
                });
                App.unblockUI($('body'));
            }
        });
    });
    //Fix location Modal
    $('.modal').each(function (i) {
        var width = $(this).data('width');
        if (width != undefined) {
            $(this).css("width", width);
            $(this).css("margin-left", -width / 2);
        }
    });

});
$(function () {
    try {
        $('.datetimepicker').datetimepicker({
            language: 'en',
            pick12HourFormat: true
        });
        $('#datetimepicker2, #datetimepicker3, #datetimepicker4, #datetimepicker5, .datetimepicker').datetimepicker({
            language: 'en',
            pick12HourFormat: true
        });
    } catch (e) {

    }
});

//function releasekrm() {
//    // Proxy created on the fly
//    var notify = $.connection.notificationHub;

//    notify.client.startRelease = function (message) {
//        App.blockUI($("body"));
//    };
//    notify.client.stopRelease = function (message) {
//        App.unblockUI($("body"));
//    };
//    $(".navbar-brand").click(function () {
//        notify.server.startRelease("Release");
//    });
//    $("body").click(function () {
//        notify.server.stopRelease("Release");
//    });
//    $.connection.hub.start();
//}

function resize_image(img, delta) {
    var el = document.getElementById(img);
    if (parseFloat(el.height) * parseFloat(delta) < 5
	|| parseFloat(el.width) * parseFloat(delta) < 5) {
        // do nothing
    }
    else {
        var h = parseInt((parseFloat(el.height) * parseFloat(delta)));
        var w = parseInt((parseFloat(el.width) * parseFloat(delta)));
        el.height = h;
        el.width = w;
    }
}

function viewTrigger(taskid) {
    $.ajax({
        url: '/scenario/trigger',
        data: { taskid: taskid },
        success: function (data) {
            $(".body-viewtrigger").html(data);
        }
    });
}

function deleteTrigger(id, taskid) {
    if (confirm('Are you sure?')) {
        $(".body-viewtrigger").html("<div class='ajax-loading'></div>");
        $.ajax({
            url: '/scenario/deletetrigger',
            data: { id: id, taskid: taskid },
            success: function (data) {
                $(".body-viewtrigger").html(data);
            }
        });
    }
}

function enableTrigger(id, taskid) {
    if (confirm('Are you sure?')) {
        $(".body-viewtrigger").html("<div class='ajax-loading'></div>");
        $.ajax({
            url: '/scenario/enabletrigger',
            data: { id: id, taskid: taskid },
            success: function (data) {
                $(".body-viewtrigger").html(data);
            }
        });
    }
}

function createtrigger() {
    $('#runtype').on("change", function () {
        var runtype = $("#runtype").val();
        if (runtype == 0) {
            $('.p-advance').hide();
            $('.panel-advance').hide();
        }
        if (runtype == 1) {
            $(".ctr-daily").show();
            $("#every").removeAttr('disabled');
            $('.p-advance').show();
        } else {
            $(".ctr-daily").hide();
            $("#every").attr('disabled', 'disabled');
        }
        if (runtype == 2) {
            $(".ctr-weekly").show();
            $("#dayinweek").removeAttr('disabled');
            $('.p-advance').show();
        } else {
            $(".ctr-weekly").hide();
            $("#dayinweek").attr('disabled', 'disabled');
        }
        if (runtype == 3) {
            $(".ctr-monthly").show();
            $("#months").removeAttr('disabled');
            $("#daysinmonths").removeAttr('disabled');
            $('.p-advance').show();
        } else {
            $(".ctr-monthly").hide();
            $("#months").attr('disabled', 'disabled');
            $("#daysinmonths").attr('disabled', 'disabled');
        }
    });
    //advance
    $(".loop-task, .stop-task, .expired").change(function () {
        if ($(".loop-task").is(':checked')) {
            $('.minutes, .choose-minutes, .hours, .choose-hours').removeAttr('disabled');
        } else {
            $('.minutes, .choose-minutes, .hours, .choose-hours').attr('disabled', 'disabled');
        }
        if ($(".stop-task").is(':checked')) {
            $('.stop-minutes, .choose-stop-minutes').removeAttr('disabled');
        } else {
            $('.stop-minutes, .choose-stop-minutes').attr('disabled', 'disabled');
        }
        if ($(".expired").is(':checked')) {
            $('.expireddate').removeAttr('disabled');
        } else {
            $('.expireddate').attr('disabled', 'disabled');
        }
    });
}

function createTrigger(taskid) {
    $('#hfTaskid').val(taskid);
}

function getSelectValMultiple() {
    $('.btn-create-trigger').click(function () {
        var lstdayinweek = "";
        var lstmonths = "";
        var lstdaysinmonths = "";

        if ($('#dayinweek').val() != undefined) {
            $('#dayinweek option:selected').each(function () {
                lstdayinweek += this.value + ", ";
            });
            $('#hfdayinweek').val(lstdayinweek);
        }
        if ($('#months').val() != undefined) {
            $('#months option:selected').each(function () {
                lstmonths += this.value + ", ";
            });
            $('#hfmonths').val(lstmonths);
        }
        if ($('#daysinmonths').val() != undefined) {
            $('#daysinmonths option:selected').each(function () {
                lstdaysinmonths += this.value + ", ";
            });
            $('#hfdaysinmonths').val(lstdaysinmonths);
        }
    });
}


function onTaskSort() {
    $(".task-filter th span").click(function () {

        $("#hfSortCol").val($(this).attr("col"));
        if ($("#hfSortDes").val() == "desc") {
            $("#hfSortDes").val("asc");
        } else {
            $("#hfSortDes").val("desc");
        }
        var p = $("a.page-active").attr("p") != undefined ? $("a.page-active").attr("p") == "1" ? "" : "&p=" + $("a.page-active").attr("p") : "";

        var sortCol = $("#hfSortCol").val() == 0 ? "" : "?sortcol=" + $("#hfSortCol").val();
        var sortDes = $("#hfSortDes").val() == 0 ? "" : "&sortdes=" + $("#hfSortDes").val();
        window.location = "scenario" + sortCol + sortDes + (p == "undefined" ? "" : p);

    });

}

function typepagechange(typepage) {
    window.location = '?typepage=' + typepage;
}

function emailchange(emailid) {
    window.location = '?EmailSubjectId=' + emailid;
}

function templatechange(templateid) {
    window.location = '?templateid=' + templateid;
}

function tasktypechange(typeid) {
    $.ajax({
        url: "/orderview/gettasktitle?typeid=" + typeid,
        success: function (data) {
            $("#TaskTitleID").html("");
            //$('<option></option>').val("0").html("--Select a title--")
            $.each(data, function (id, option) {
                $("#TaskTitleID").append($('<option></option>').val(option.Id).html(option.Name));
            });
        }
    });
}

function companychange(orderid, companyid) {
    window.location = '?orderid=' + orderid + '&companyid=' + companyid;
}

function changedepartment(userid) {
    $.ajax({
        url: '/users/changedepartment',
        data: { userid: userid },
        success: function (data) {
            $("#changedepartment").html(data);
        }
    });
}

function PopupCenter(pageURL, w, h) {
    var left = (screen.width / 2) - (w / 2);
    var top = (screen.height / 2) - (h / 2) - 50;
    return window.open(pageURL, 'popup', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=1, resizable=1, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
}

function Popup(pageURL, w, h) {
    return window.open(pageURL, 'popup', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=1, resizable=1, copyhistory=no, width=' + w + ', height=' + h);
}

function windowclose() {
    window.close();
}

function closeandreload() {
    window.close();
    window.opener.location.reload();
}

function CancelRdm(disputeid, orderid, name) {
    if (confirm('Are you sure you wish to delete the selected RDM for item ' + name + '?')) {
        $(".rdm").html("<div class=\"ajax-loading\"></div>");
        $.ajax({
            url: "/rdm/CancelRdm",
            data: { id: disputeid, orderid: orderid },
            success: function (data) {
                $(".rdm").html(data);
            }
        });
    }
}

function validCardNum(cardnum) {
    $.ajax({
        url: '/orderview/CheckCardNum',
        data: { cardNum: cardnum },
        dataType: "bool",
        success: function (data) {
            return true;
        },
        error: function () {
            alert('The new credit card number is not valid and will fail');
            return false;
        }
    });
}

function limitText(limitField) {
    if (limitField.value.length > 160) {
        limitField.value = limitField.value.substring(0, 160);
    } else {
        $('.textcount').html((160 - limitField.value.length) + "/160");
    }
}

function productchange(productid) {
    App.blockUI($("#fr-addvideo").parent(), false);
    $("#hfproductid").val(productid);
    $.ajax({
        url: "/products/getvideobyproduct?productid=" + productid,
        success: function (data) {
            $("#fr-addvideo").html(data);
            App.unblockUI($("#fr-addvideo").parent());
        }, error: function () {
            alert("Error");
            App.unblockUI($("#fr-addvideo").parent());
        }
    });
}
// dataTables
function LoadDataTable($dttb) {
    var oTable = $($dttb).dataTable({
        "iDisplayLength": 10000,
        "sScrollY": $dttb.attr("data-height"),
        "sScrollX": "100%",
        "aaSorting": []
             
    });
    $('.dataTables_paginate').remove();
}

var radius = 0;
function gadientlogo(logo) {
    if (radius == 0 || radius >= 144 ) {
        radius = 0;
        var interval = window.setInterval(function () {
            logo.css("-webkit-mask", "-webkit-gradient(radial, 17 17, " + (radius - 5) + ", 17 17, " + (radius + 10) + ", from(rgb(0, 0, 0)), color-stop(0.1, rgba(0, 0, 0, 0.2)), to(rgb(0, 0, 0)))");
            radius++;
            if (radius >= 144) {
                radius = 0;
                window.clearInterval(interval);
            }
        }, 10);
    }

}

(function ($) {

    /**
     * Confirm a link or a button
     * @param [options] {{title, text, confirm, cancel, confirmButton, cancelButton, post, confirmButtonClass}}
     */
    $.fn.confirm = function (options) {
        if (typeof options === 'undefined') {
            options = {};
        }

        this.click(function (e) {
            e.preventDefault();

            var newOptions = $.extend({
                button: $(this)
            }, options);

            $.confirm(newOptions, e);
        });

        return this;
    };

    /**
     * Show a confirmation dialog
     * @param [options] {{title, text, confirm, cancel, confirmButton, cancelButton, post, confirmButtonClass}}
     * @param [e] {Event}
     */
    $.confirm = function (options, e) {
        // Do nothing when active confirm modal.
        if ($('.confirmation-modal').length > 0)
            return;

        // Parse options defined with "data-" attributes
        var dataOptions = {};
        if (options.button) {
            var dataOptionsMapping = {
                'title': 'title',
                'text': 'text',
                'confirm-button': 'confirmButton',
                'cancel-button': 'cancelButton',
                'confirm-button-class': 'confirmButtonClass'
            };
            $.each(dataOptionsMapping, function (attributeName, optionName) {
                var value = options.button.data(attributeName);
                if (value) {
                    dataOptions[optionName] = value;
                }
            });
        }

        // Default options
        var settings = $.extend({}, $.confirm.options, {
            confirm: function () {
                var url = e && (('string' === typeof e && e) || (e.currentTarget && e.currentTarget.attributes['href'].value));
                if (url) {
                    if (options.post) {
                        var form = $('<form method="post" class="hide" action="' + url + '"></form>');
                        $("body").append(form);
                        form.submit();
                    } else {
                        window.location = url;
                    }
                }
            },
            cancel: function (o) {
            },
            button: null
        }, dataOptions, options);

        // Modal
        var modalHeader = '';
        if (settings.title !== '') {
            modalHeader =
                '<div class=modal-header>' +
                    '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' +
                    '<h4 class="modal-title">' + settings.title + '</h4>' +
                '</div>';
        }
        var modalHTML =
                '<div class="confirmation-modal modal fade" tabindex="-1" role="dialog">' +
                    '<div class="modal-dialog">' +
                        '<div class="modal-content">' +
                            modalHeader +
                            '<div class="modal-body">' + settings.text + '</div>' +
                            '<div class="modal-footer">' +
                                '<button class="confirm btn ' + settings.confirmButtonClass + '" type="button" data-dismiss="modal">' +
                                    settings.confirmButton +
                                '</button>' +
                                '<button class="cancel btn btn-default" type="button" data-dismiss="modal">' +
                                    settings.cancelButton +
                                '</div>' +
                            '</div>' +
                        '</div>' +
                    '</div>' +
                '</div>';

        var modal = $(modalHTML);

        modal.on('shown.bs.modal', function () {
            modal.find(".btn-primary:first").focus();
        });
        modal.on('hidden.bs.modal', function () {
            modal.remove();
        });
        modal.find(".confirm").click(function () {
            settings.confirm(settings.button);
        });
        modal.find(".cancel").click(function () {
            settings.cancel(settings.button);
        });

        // Show the modal
        $("body").append(modal);
        modal.modal('show');
    };

    /**
     * Globally definable rules
     */
    $.confirm.options = {
        text: "Are you sure?",
        title: "",
        confirmButton: "Yes",
        cancelButton: "Cancel",
        post: false,
        confirmButtonClass: "btn-primary"
    }
})(jQuery);
